package javaweb;

import org.junit.Test;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class TCP_V1 {
    @Test
    public void Client(){
        Socket socket = null;
        ByteArrayOutputStream bos = null;
        InputStream is = null;
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("user.txt"))
        ){
            InetAddress host = InetAddress.getByName("localhost");
            socket = new Socket(host, 8088);
            OutputStream os = socket.getOutputStream();
            //客户端发送读取的数据
            int len;
            byte[] bytes=new byte[1024];
            while ((len=bis.read(bytes))!=-1){
                os.write(bytes,0,len);
            }
            //read()导致方法阻塞,须手动关闭流告知服务器发送完成
            socket.shutdownOutput();
            System.out.println("发送完毕");
            //读取服务器的反馈
            is = socket.getInputStream();
            bos = new ByteArrayOutputStream();
            while ((len=is.read(bytes))!=-1){
                bos.write(bytes,0,len);
            }
            System.out.println(bos.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
                bos.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @Test
    public void Server(){
        ServerSocket serverSocket = null;
        InputStream is = null;
        try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("users.txt",true))){
            serverSocket = new ServerSocket(8088);
            Socket accept = serverSocket.accept();
            //接收数据
            is = accept.getInputStream();
            //保存数据到本地
            byte[] bytes=new byte[1024];
            int len;
            while ((len=is.read(bytes))!=-1){
                bos.write(bytes,0,len);
            }
            System.out.println("接收完毕");
            //发送服务器的反馈
            OutputStream os = accept.getOutputStream();
            os.write("收到了".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                serverSocket.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
